package com.sysu.ooad.service.impl;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.sysu.ooad.dao.GroupDao;
import com.sysu.ooad.dao.StudentDao;
import com.sysu.ooad.entity.Course;
import com.sysu.ooad.entity.Group;
import com.sysu.ooad.entity.Student;
import com.sysu.ooad.service.GroupService;

@Component("groupService")
public class GroupServiceImpl implements GroupService{

	private GroupDao groupDao;
	private StudentDao studentDao;
	
	public GroupDao getGroupDao() {
		return groupDao;
	}

	@Resource
	public void setGroupDao(GroupDao groupDao) {
		this.groupDao = groupDao;
	}

	public StudentDao getStudentDao() {
		return studentDao;
	}

	@Resource
	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}

	public boolean create(Student s, String groupName) {
		Group group = new Group();
		group.setName(groupName);
		group.setLeader(s);
		group.setCourse(s.getCourse());
		group.setLocked(false);
		groupDao.add(group);
		s.setGroup(group);
		studentDao.update(s);
		return true;
	}

	public boolean join(Student s, Group g) {
		s.setGroup(g);
		studentDao.update(s);
		return true;
	}

	public boolean leave(Student s) {
		if(s.isGroupLeader()) {
			return false;
		}
		s.setGroup(null);
		studentDao.update(s);
		return true;
	}

	public List<Group> findByCourse(Course c) {
		return groupDao.findByCourse(c);
	}

	public Group getById(Integer id) {
		return groupDao.getById(id);
	}

	public boolean dissolve(Group g) {
//		Set<Student> students = g.getStudents();
		List<Student> students = studentDao.findByGroup(g);
		for(Student s : students) {
			s.setGroup(null);
			studentDao.update(s);
		}
		
		g.setStudents(null);
		g.setCourse(null);
		g.setLeader(null);
		groupDao.delete(g);
		
		for(Student s : students) {
			s.setGroup(null);
			studentDao.update(s);
		}
		
		return true;
	}

	public boolean lockAll(Course c, boolean locked) {
		List<Group> groups = groupDao.findByCourse(c);
		for(Group g : groups) {
			g.setLocked(locked);
			groupDao.update(g);
		}
		return true;
	}

	public boolean lock(Group g, boolean toLock) {
		g.setLocked(toLock);
		groupDao.update(g);
		return false;
	}
}
